import { BaseContext } from 'koa';
import { getRepository, Repository,  } from "typeorm";
import { validate, ValidationError } from "class-validator";
import { JWT } from '../../utils/jwt';
import { config } from '../../config/config';
import { User } from "../../database/entity/user";

async function loginUtil(ctx: BaseContext,_name: string,_password: string) {
    const name: string = _name;
    const password: string = _password;
    const userRepository: Repository<User> = getRepository(
        User
    );

    const user: User = await userRepository.findOne({
        name,
    });

    if (user) {
        const id: number = user.id;
        if(user.password === password) {
            const now: number = new Date().getTime();
            const exp = now + 1000*60*60*2;
            const iss: string = config.jwtIssuer;
            const iat: number = now;
            const jwtfunc = new JWT();
            let payload = {
                name,
                iss,
                iat,
                exp
            };
            let token = jwtfunc.sign({
                payload
            });

            user.token = token;
            const errors: ValidationError[] = await validate(user);
            if (errors.length > 0) {
                ctx.status = 200;
                ctx.app.emit('error',{
                    code: ctx.ERROR.ERRORCODE_SYSTEMERROR,
                    message: errors.toString(),
                },ctx);
            } else if (!(await userRepository.findOne({id: user.id}))) {
                ctx.status = 200;
                ctx.app.emit('error',{
                    code: ctx.ERROR.ERRORCODE_SYSTEMERROR,
                    message: "更新的用户不存在",
                },ctx);
            }else {
                ctx.status = 200;
                await userRepository.save(user);
                const avater: string = user.avater;
                ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_SUCCESS,{
                    name,
                    token,
                    avater,
                    id,
                });
            }
        }else {
            ctx.status = 200;
            ctx.app.emit('error',{
                code: ctx.ERROR.ERRORCODE_ERRORPWD,
                message: ctx.ERROR.ERRORMSG_ERRORPWD,
            },ctx);
        }
    } else {
        ctx.status = 500;
        ctx.app.emit('error',{
            code: ctx.ERROR.ERRORCODE_NOUSER,
            message: ctx.ERROR.ERRORMSG_NOUSER,
        },ctx);
    }
}

export { loginUtil };